package com.zn.handler;

import com.zn.entity.Request;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 对请求进行处理，就是将请求这个字符串截串，分装成一个对象
 * @Author: zhangnan
 * @Date: 2019/11/23
 */
public class RequestHandler {

    public Request requestHandler(Socket socket) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = socket.getInputStream();

        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        sb.append(new String(bytes, 0, len));

        String[] headerAndBody = sb.toString().split("\r\n\r\n");

        String[] split = headerAndBody[0].split("\r\n");
        String[] typeSplit = split[0].split(" ");

        Request request = new Request();
        request.setRequestType(typeSplit[0]);
        request.setUrl(typeSplit[1]);
        request.setProtocolType(typeSplit[2]);

        Map<String, String> map = new HashMap<>(16);
        for (int i = 1; i < split.length; i++) {
            if( split[i] == null || "".equals(split[i]) ){
                break;
            }
            String[] others = split[i].split(": ");
            map.put(others[0], others[1]);
            request.setMap(map);
        }

        if(headerAndBody.length == 2){
            request.setRequestBody(headerAndBody[1]);
        }

        return request;
    }
}
